<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2019-04-09
 * Time: 15:53
 */

namespace app\api\controller;


use app\service\AddressService;
use app\common\model\Area;

class Address extends Base
{
   //收货地址首页
    public function index(){
        $where['uid']=$this->uid;
        $addressInfo=AddressService::S()->selectAddress($this->uid);
        $this->ajax(200,'success',$addressInfo);
    }


    //修改收货地址
    public function save_address(){
        $id=input('post.id');
        if(!empty($id)){
            $prevAddress=AddressService::S()->findAddress(array('id'=>$id),'uid');
            if($prevAddress['uid']!=$this->uid){
                $this->ajax(202,'传入的ID不符合修改要求');
            }
        }else{
            $id=null;
        }
        $save['name']=input('post.name');
        $save['mobile']=input('post.mobile');
        if(!checkMobile($save['mobile'])){
            $this->ajax(202,'手机号码不正确');
        }
        $save['province']=input('post.province');
        $save['city']=input('post.city');
        $save['county']=input('post.county');
        $save['address']=input('post.address');
        $save['is_default']=input('post.is_default')==1?1:0;
        $save['uid']=$this->uid;
        $re=AddressService::S()->add($save,$id);
        if($re===false){
            $this->ajax(202,'新增失败');
        }else{
            $this->ajax(200,'新增收货地址成功');
        }
    }


    //删除收货地址
    public function del_address(){
        $id=input('post.address_id');
        $re=AddressService::S()->delAddress($id,$this->uid);
        if($re){
            $this->ajax(200,'删除成功');
        }else{
            $this->ajax(200,'删除失败');
        }
    }

    /* 全国省/市/区 列表 */
    public function area () {
        $input = input();
        if(!$input['parentid']) {
            $this->ajax(202,'error');
        }
        $list = Area::getAll([
            'parentid' => $input['parentid']
        ],'id asc','id,name,parentid');
        $this->ajax(200,'success',$list);
    }
}